// tslint:disable:space-before-function-paren
import { AnyAction } from 'redux';
import { List } from 'immutable';
import { put, take, fork } from 'redux-saga/effects';
import { runApiSaga, authApiFetch, util, handleApiErrorViaMessage } from '../../../../common';
import {
    BEGIN_LOAD_WORKER, LOAD_WORKER
} from './constants';
import {
    syncWorker, workerLoading
} from './actions';
// import {
//     makeSelectFilter
// } from './selectors';

function* doLoad() {
    yield put(workerLoading(true));

    const records = yield authApiFetch(
        'worker/list',
        'POST',
        {});

    yield put(syncWorker(records));

    yield put(workerLoading(false));
}

function* doLoadLoop() {
    // TODO: 这里会不会在切完地址之后继续死循环
    while (true) {
        yield doLoad();

        yield util.sleepWithSaga(__DEV__ ? 5000 : 5 * 60 * 1000);
    }
}

export default function* init() {
    const handleActions = List([BEGIN_LOAD_WORKER, LOAD_WORKER]);
    let des = null;
    // while (des = yield take('*')) {  // 建议仅在主页面进行 * 号拦截
    while (des = yield take((action: AnyAction) => handleActions.includes(action.type))) {
        switch (des.type) {
            case LOAD_WORKER:
                yield runApiSaga(doLoad, des.payload);
                break;
            case BEGIN_LOAD_WORKER:
                // tslint:disable-next-line:space-before-function-paren
                yield fork(function* (payload: any) {
                    yield runApiSaga(doLoadLoop, payload, handleApiErrorViaMessage, true);
                }, des.payload);
                break;
        }
    }
}
